<template>
  <KView class="payment-address">
    <page-header title="我的收货地址" @back-click="toBack">
      <KView class="payment-address-add" @click="toAdd">新增</KView>
    </page-header>
    <KView class="payment-address-line"></KView>

    <KView class="payment-address-content" v-if="isShow">
      <template v-if="addressList.length>0">
        <address-item v-for="address in addressList" :key="`address_${address.id}`" :address="address" :default-address="defaultAddress"
          @change-default="changeDefault" @update-address="toUpdate" @delete-address="toDelete">
        </address-item>
      </template>
      <KView v-else class="payment-address-nodata flex-central">
        <KView>暂无收货地址</KView>
      </KView>
    </KView>
  </KView>
</template>

<script>
  import SystemUtil from 'utils/systemUtil';

  import PageHeader from 'common/pageHeader';
  import AddressItem from './addressItem';

  import GoodsPaymentApi from 'services/goodsPaymentApi';

  export default {
    data() {
      let pages = getCurrentPages();
      let payWin = pages[pages.length - 2].window;
      return {
        isShow: false,
        payWin,
        addressList: [],
        defaultAddress: null,
        isMiniprogram: process.env.isMiniprogram
      };
    },

    created() {
      SystemUtil.showLoading();
      this.setAddressList().then(() => {
        this.isShow = true;
        SystemUtil.hideLoading();
      }).catch(() => {
        SystemUtil.hideLoading();
      });
    },

    methods: {
      setAddressList(isChangeDefault = false) {
        return GoodsPaymentApi.getGoodsAddressList().then(res => {
          this.addressList = res.addressList;
          this.defaultAddress = res.defaultAddress;
          if (isChangeDefault) {
            this.payWin.resetAddress(res.defaultAddress);
          }
          return res;
        });
      },

      toAdd() {
        let url = '/addAddress';
        if (this.isMiniprogram) {
          window.open(url);
        }
      },

      toUpdate(address) {
        let url = `/updateAddress/${address.id}`;
        if (this.isMiniprogram) {
          window.open(url);
        }
      },

      toDelete(address) {
        this.$api.showModal({
          content: '确定要删除该地址吗？',
          success: res => {
            if (res.confirm) {
              this.deleteAddress(address);
            }
          }
        });
      },

      deleteAddress(address) {
        SystemUtil.showLoading('');
        GoodsPaymentApi.deleteAddress(address.id).then(() => {
          SystemUtil.hideLoading();
          return this.setAddressList().then(() => {
            let defaultAddress = this.defaultAddress;
            if (defaultAddress === null) {
              let addressList = this.addressList;
              if (addressList.length > 0) {
                return this.changeDefault(addressList[0]);
              } else {
                this.payWin.resetAddress(null);
              }
            }
          });
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      changeDefault(address) {
        let defaultAddress = this.defaultAddress;
        if (address === defaultAddress) {
          return window.Promise.reject();
        }

        SystemUtil.showLoading('');
        return GoodsPaymentApi.changeDefault(address.id).then(() => {
          if (defaultAddress !== null) {
            defaultAddress.isDefault = false;
          }
          address.isDefault = true;
          this.defaultAddress = address;
          this.payWin.resetAddress(address);
          SystemUtil.hideLoading();
          return true;
        }).catch(() => {
          SystemUtil.hideLoading();
          throw false;
        });
      },

      resetData(data) {
        let type = data.type;
        let isChangeDefault = false;
        if (type === 'add') {
          if (this.addressList.length === 0) {
            isChangeDefault = true;
          }
        } else if (type === 'update') {
          if (this.defaultAddress.id === data.id) {
            isChangeDefault = true;
          }
        }

        SystemUtil.showLoading();
        this.setAddressList(isChangeDefault).then(() => {
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      toBack() {
        if (!this.isMiniprogram) {
          window.history.back();
          return;
        }
        wx.navigateBack();
      }
    },

    components: {
      PageHeader,
      AddressItem
    }
  };

</script>

<style lang="scss">
  .payment-address {
    height: 100%;

    .page-header {
      margin-bottom: formatPx(20);

      .payment-address-add {
        position: absolute;
        right: formatPx(30);
        bottom: 0;
        font-size: formatPx(26);
      }
    }

    .payment-address-line {
      height: 1px;
      background: #DADADA;
    }

    .payment-address-content {
      margin-top: formatPx(40);
      height: calc(100% - #{formatPx(170)});
      padding: formatPx(16) formatPx(30);
      overflow: auto;

      .payment-address-nodata {
        color: #58595b;
        height: 100%;
      }

      .address-item {
        margin-bottom: formatPx(30);

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

</style>
